package servlet;

import entity.Book;
import entity.Page;
import entity.User;
import service.BookService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "QueryBookByPageServlet", value = "/QueryBookByPageServlet")
public class QueryBookByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String currentPage=request.getParameter("currentPage");
        String search=request.getParameter("search_");
        BookService bookService=new BookServiceImpl();
        Page page=new Page();
        currentPage=(currentPage==null?"0":currentPage);
        page.setCurrentPage(Integer.parseInt(currentPage));
        if(search==null||"null".equals(search)){  //search用来判断是查询全部还是条件查询
            String sql="select count(*) from books";
            int count=bookService.getBookTotalCount(sql,null);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<Book> books=bookService.queryBookByPage(page.getCurrentPage(), page.getPageSize());
            page.setBook(books);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search_",search);
            request.getRequestDispatcher("book.jsp").forward(request,response);
        }else{
            String sql="select count(*) from books where bookId=? or bookName=?";
            Object[] params={search,search};
            int count=bookService.getBookTotalCount(sql,params);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<Book> books=bookService.queryBookByPageRequire(page.getCurrentPage(), page.getPageSize(), search);
            page.setBook(books);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search_",search);
            request.getRequestDispatcher("book.jsp").forward(request,response);
        }
    }
}
